package com.example.smartwaterapi.controller;

import com.example.smartwaterapi.common.api.RestApiResponse;
import com.example.smartwaterapi.entity.User;
import com.example.smartwaterapi.security.JwtTokenUtil;
import com.example.smartwaterapi.security.SecurityUser;
import com.example.smartwaterapi.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 认证控制器
 */
@Slf4j
@Tag(name = "认证管理", description = "用户登录和认证相关接口")
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Value("${jwt.header}")
    private String tokenHeader;
    
    @Value("${jwt.token-head}")
    private String tokenHead;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Operation(summary = "用户登录", description = "使用手机号和密码登录")
    @PostMapping("/login")
    public RestApiResponse<Map<String, Object>> login(@RequestBody @Valid LoginRequest loginRequest) {
        try {
            // 进行身份验证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getPhone(), loginRequest.getPassword()));

            // 将认证信息存入SecurityContext
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 获取SecurityUser
            SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
            User user = securityUser.getUser();

            // 生成JWT令牌
            String token = jwtTokenUtil.generateToken(securityUser);

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("tokenHead", tokenHead);
            
            // 用户信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("phone", user.getPhone());
            userInfo.put("nickname", user.getNickname());
            userInfo.put("avatar", user.getAvatar());
            userInfo.put("gender", user.getGender());
            result.put("userInfo", userInfo);

            return RestApiResponse.ok("登录成功", result);
        } catch (BadCredentialsException e) {
            log.warn("登录失败: {}", e.getMessage());
            return RestApiResponse.badRequest("手机号或密码错误");
        }
    }

    @Operation(summary = "用户注册", description = "用户注册接口")
    @PostMapping("/register")
    public RestApiResponse<Map<String, Object>> register(@RequestBody @Valid RegisterRequest registerRequest) {
        // 检查手机号是否已被注册
        User existUser = userService.getByPhone(registerRequest.getPhone());
        if (existUser != null) {
            return RestApiResponse.badRequest("该手机号已被注册");
        }

        // 创建用户
        User user = new User();
        user.setPhone(registerRequest.getPhone());
        user.setNickname(registerRequest.getNickname());
        user.setUnlockPassword(passwordEncoder.encode(registerRequest.getPassword()));
        user.setPasswordSalt(UUID.randomUUID().toString().replace("-", ""));
        user.setUuid(UUID.randomUUID().toString().replace("-", ""));
        user.setStatus(1);
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        
        // 设置默认值
        user.setDailyGoal(2000); // 默认2000ml饮水目标
                    user.setReminderEnabled(0); // 🔕 默认关闭提醒，避免打扰用户
        user.setReminderInterval(60); // 默认提醒间隔1小时
        user.setPoints(0);
        user.setTotalPoints(0);
        
        // 保存用户
        boolean success = userService.save(user);
        if (!success) {
            return RestApiResponse.error("注册失败，请稍后再试");
        }

        // 自动登录
        try {
            // 进行身份验证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(registerRequest.getPhone(), registerRequest.getPassword()));

            // 将认证信息存入SecurityContext
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 获取SecurityUser
            SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();

            // 生成JWT令牌
            String token = jwtTokenUtil.generateToken(securityUser);

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("tokenHead", tokenHead);
            
            // 用户信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("phone", user.getPhone());
            userInfo.put("nickname", user.getNickname());
            result.put("userInfo", userInfo);

            return RestApiResponse.created("注册成功", result);
        } catch (Exception e) {
            log.error("自动登录失败: {}", e.getMessage());
            // 创建一个空的Map作为返回值
            Map<String, Object> emptyResult = new HashMap<>();
            return RestApiResponse.created("注册成功，请登录", emptyResult);
        }
    }

    @Operation(summary = "刷新令牌", description = "刷新JWT令牌")
    @GetMapping("/refreshToken")
    public RestApiResponse<Map<String, String>> refreshToken(@RequestHeader(value = "${jwt.header}") String authHeader) {
        // 判断token格式
        if (authHeader == null || !authHeader.startsWith(tokenHead + " ")) {
            return RestApiResponse.badRequest("token格式不正确");
        }
        
        // 获取token
        String token = authHeader.substring(tokenHead.length() + 1);
        
        // 解析用户名
        String username = jwtTokenUtil.getUsernameFromToken(token);
        if (username == null) {
            return RestApiResponse.unauthorized("token已过期或无效");
        }
        
        // 生成新token
        SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String newToken = jwtTokenUtil.generateToken(securityUser);
        
        Map<String, String> result = new HashMap<>();
        result.put("token", newToken);
        result.put("tokenHead", tokenHead);
        
        return RestApiResponse.ok(result);
    }
    
    /**
     * 登录请求对象
     */
    @Data
    public static class LoginRequest {
        @NotBlank(message = "手机号不能为空")
        private String phone;
        
        @NotBlank(message = "密码不能为空")
        private String password;
    }
    
    /**
     * 注册请求对象
     */
    @Data
    public static class RegisterRequest {
        @NotBlank(message = "手机号不能为空")
        private String phone;
        
        @NotBlank(message = "密码不能为空")
        private String password;
        
        @NotBlank(message = "昵称不能为空")
        private String nickname;
    }
} 